package com.lw.lost.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.MenuItem
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.lw.lost.R
import com.lw.lost.databinding.ActivityPersonalInfoBinding
import com.lw.lost.db.DBlost
import com.lw.lost.utils.PreferenceUtils
import com.google.android.material.textfield.MaterialAutoCompleteTextView

class PersonalInfoActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPersonalInfoBinding
    private lateinit var db: DBlost
    private var selectedImageUri: Uri? = null

    private val getContent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.data?.let { uri ->
                selectedImageUri = uri
                Glide.with(this)
                    .load(uri)
                    .placeholder(R.drawable.ic_profile)
                    .error(R.drawable.ic_profile)
                    .into(binding.ivAvatar)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPersonalInfoBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 设置Toolbar
        binding.toolbar.apply {
            title = "个人资料"
            setNavigationIcon(R.drawable.ic_back) // 确保你有这个图标
            setNavigationOnClickListener {
                finish()
            }
        }

        db = DBlost(this)
        initViews()
        loadUserInfo()
    }

    private fun initViews() {
        // 设置学历选项
        val educationOptions = arrayOf("小学", "初中", "高中", "中专", "大专", "本科", "硕士", "博士")
        
        (binding.spinnerEducation as MaterialAutoCompleteTextView).apply {
            setSimpleItems(educationOptions)
            setText(educationOptions[0], false)
            
            // 添加选择监听器
            setOnItemClickListener { _, _, position, _ ->
                val selectedEducation = educationOptions[position]
                // 处理选择事件
            }
        }

        // 头像编辑点击事件
        binding.ivEditAvatar.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            getContent.launch(intent)
        }

        // 保存按钮点击事件
        binding.btnSave.setOnClickListener {
            saveUserInfo()
        }
    }

    private fun loadUserInfo() {
        val userId = PreferenceUtils.getUserId(this)
        val cursor = db.userDao.getUserById(userId)
        
        if (cursor.moveToFirst()) {
            binding.etName.setText(cursor.getString(cursor.getColumnIndexOrThrow("name")))
            binding.etAge.setText(cursor.getInt(cursor.getColumnIndexOrThrow("age")).toString())
            
            val gender = cursor.getInt(cursor.getColumnIndexOrThrow("gender"))
            if (gender == 0) binding.rbMale.isChecked = true
            else binding.rbFemale.isChecked = true

            // 加载头像
            val avatarPath = cursor.getString(cursor.getColumnIndexOrThrow("avatar"))
            if (!avatarPath.isNullOrEmpty()) {
                Glide.with(this)
                    .load(avatarPath)
                    .placeholder(R.drawable.ic_profile)
                    .error(R.drawable.ic_profile)
                    .into(binding.ivAvatar)
            }
        }
        cursor.close()

        // 加载兴趣信息
        val interestCursor = db.interestDao.getInterestsByUserId(userId)
        if (interestCursor.moveToFirst()) {
            // 使用setText方式设置值
            (binding.spinnerEducation as MaterialAutoCompleteTextView).setText(
                interestCursor.getString(interestCursor.getColumnIndexOrThrow("education")),
                false
            )
            binding.etInterests.setText(
                interestCursor.getString(interestCursor.getColumnIndexOrThrow("content"))
            )
        }
        interestCursor.close()
    }

    private fun saveUserInfo() {
        val userId = PreferenceUtils.getUserId(this)
        val name = binding.etName.text.toString()
        val age = binding.etAge.text.toString()
        val gender = if (binding.rbMale.isChecked) 0 else 1
        val education = binding.spinnerEducation.text.toString()
        val interests = binding.etInterests.text.toString()

        // 验证输入
        if (name.isEmpty() || age.isEmpty() || education.isEmpty() || interests.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show()
            return
        }

        // 更新用户信息
        val values = android.content.ContentValues().apply {
            put("name", name)
            put("age", age.toInt())
            put("gender", gender)
            selectedImageUri?.let { put("avatar", it.toString()) }
        }
        db.userDao.updateUser(userId, values)

        // 更新兴趣信息
        val interestValues = android.content.ContentValues().apply {
            put("education", education)
            put("content", interests)
        }
        db.interestDao.updateInterest(userId, interestValues)

        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
        finish()
    }
} 